<?php

namespace app\controller\Study;
use app\BaseController;
use app\Models\Study\CourseModel;
use app\Models\Study\TeacherModel;
use think\Exception;
use think\facade\Db;
use think\Request;

class TeacherController extends BaseController
{
    public function transaction(Request $request)
    {
        //启动事务
        Db::startTrans();
        try {
            $time = time();
            //插入教师 A 信息
            $teacherModel             = new TeacherModel();
            $teacherModel->name       = $request->param("name", "");
            $teacherModel->age        = $request->param("age", 0, "intval");
            $teacherModel->id_number  = $request->param("id_number", "");
            $teacherModel->created_at = $time;
            $teacherModel->save();

            //插入 A 教师课程相关相关信息
            $courseModel              = new CourseModel();
            $courseModel->course_name = $request->param("course_name");
            $courseModel->teacher_id  = $teacherModel->id;//上面插入教师产生的 id
            $courseModel->created_at  = $time;
            $courseModel->save();

            //提交事务
            Db::commit();
        } catch (\Exception $exception) { //捕获异常
            //若出现异常错误则回滚事务
            Db::rollback();
            throw new Exception($exception->getMessage());//抛出错误异常
        }

        return json("请求成功");
    }
}